﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using MiniJSONx;

public class ItemHelper {

	public static Dictionary<int, ExogenesisItem> EXOGENESIS_ITEMS;
	public static List<ItemCombination> ITEM_COMBINATIONS;

	//Load ALL the items in a List- Do ths first before everything
	public static void LoadItemList()
	{
//		if(EXOGENESIS_ITEMS != null)
//			EXOGENESIS_ITEMS.Clear();

		EXOGENESIS_ITEMS = new Dictionary<int, ExogenesisItem>();

		TextAsset itemData = Resources.Load("Item-Data", typeof(TextAsset)) as TextAsset;

		Hashtable ht = Json.Deserialize(itemData.text) as Hashtable;
		ArrayList jsonContents = ht["Items"] as ArrayList;

		foreach(Hashtable item in jsonContents)
		{
			ExogenesisItem toAdd = new ExogenesisItem();

			toAdd.ID = int.Parse(item["id"].ToString());
			toAdd.Name = item["name"].ToString();
			toAdd.ImagePath = item["image"].ToString();
			toAdd.Description = item["description"].ToString();

			EXOGENESIS_ITEMS.Add(toAdd.ID, toAdd);
		}

//		if(ITEM_COMBINATIONS != null)
//			ITEM_COMBINATIONS.Clear();

		ITEM_COMBINATIONS = new List<ItemCombination>();

		ArrayList jsonContents2 = ht["Combinations"] as ArrayList;

		foreach(Hashtable combination in jsonContents2)
		{
			ItemCombination toAdd = new ItemCombination();

			ArrayList ingredientsRaw = combination["ingredients"] as ArrayList;

			int productKey = int.Parse(combination["product"].ToString());

			ExogenesisItem product = EXOGENESIS_ITEMS[productKey];
			toAdd.Item_Product = product;

			Debug.Log("Found " + product.Name + " has " + ingredientsRaw.Count.ToString() + " ingredients");

			int currIndex = 0;

			foreach(object ingredient in ingredientsRaw)
			{
				int itemKey = int.Parse(ingredient.ToString());
				ExogenesisItem ingredientItem = EXOGENESIS_ITEMS[itemKey];

				toAdd.Item_Ingredients.Add(ingredientItem);
			}

			ITEM_COMBINATIONS.Add(toAdd);
		
		}

		Debug.Log("Items loaded " + EXOGENESIS_ITEMS.Values.Count + " items " + ITEM_COMBINATIONS.Count + " combinations");
	}


	//Saves a text file in the Resources folder named Item-Data.txt... Only works in editor mode
	public static void SaveItemList()
	{
		Debug.Log(Application.dataPath + "/Resources/Item-Data.txt");
		string filePath = Application.dataPath + "/Resources/Item-Data.txt";
		StreamWriter fileWriter = new StreamWriter(filePath);

		fileWriter.Write(ConvertDictionaryToJSON());

		fileWriter.Close();
	}

	///// <summary>
	/// Gets the first instance of a combination given the ingrediens</summary>
	/// <returns>The item combination by name. NULL if none found...</returns>
	/// <param name="Ingredients">What to search for.</param>
	public static ItemCombination GetItemCombination(List<ExogenesisItem> Ingredients)
	{
		foreach(ItemCombination combi in ITEM_COMBINATIONS)
		{
			if(combi.IsValidCombination(Ingredients))
				return combi;
		}

		return null;
	}

	public static ExogenesisItem GetItemProductByIngredients(List<ExogenesisItem> Ingredients)
	{
		ItemCombination combi = GetItemCombination(Ingredients);
		return combi.Item_Product;
	}

	///// <summary>
	/// Gets the first instance of an item that contains the key in its name</summary>
	/// <returns>The item by name. NULL if none found...</returns>
	/// <param name="key">What to search for.</param>
	public static ExogenesisItem GetItemByName(string key)
	{
		foreach(var item in EXOGENESIS_ITEMS)
		{
			if(item.Value.Name.Contains(key))
				return item.Value;
		}

		return null;
	}

	///// <summary>
	/// Gets the first instance of an item by ID</summary>
	/// <returns>The item by id. NULL if none found...</returns>
	/// <param name="key">ID.</param>
	public static ExogenesisItem GetItemByID(int key)
	{
		if(EXOGENESIS_ITEMS.ContainsKey(key))
			return EXOGENESIS_ITEMS[key];
		else
			return null;
	}

	//What it says on the tin....
	public static string ConvertDictionaryToJSON()
	{

		string ret = "{\n" + 
						"\t\"Items\" : [\n";

		ExogenesisItem[] itemsToWrite = new ExogenesisItem[EXOGENESIS_ITEMS.Values.Count];
		EXOGENESIS_ITEMS.Values.CopyTo(itemsToWrite,0);

		for(int i = 0; i < itemsToWrite.Length; i++)
		{
			ret = ret + "\t\t{\n";
			ret = ret + "\t\t\t\"id\" : \"" + itemsToWrite[i].ID + "\",\n";
			ret = ret + "\t\t\t\"name\" : \"" + itemsToWrite[i].Name + "\",\n";
			ret = ret + "\t\t\t\"image\" : \"" + itemsToWrite[i].ImagePath + "\",\n";
			ret = ret + "\t\t\t\"description\" : \"" + itemsToWrite[i].Description + "\",\n";
			ret = ret + "\t\t}";

			if(i != itemsToWrite.Length - 1)
				ret = ret + ",\n";
		}

		ret = ret + "\n\t],\n";

		ret = ret + "\"Combinations\" : [ \n";

		ItemCombination[] itemCombinations = new ItemCombination[ITEM_COMBINATIONS.Count];
		ITEM_COMBINATIONS.CopyTo(itemCombinations, 0);

		for(int i = 0; i < itemCombinations.Length; i++)
		{
			ItemCombination combination = itemCombinations[i];
			ExogenesisItem[] ingredients = new ExogenesisItem[combination.Item_Ingredients.Count];

			combination.Item_Ingredients.CopyTo(ingredients, 0);

			ret = ret + "\t\t{\n";
			ret = ret + "\t\t\t\"ingredients\" : [";

			for(int h = 0; h < ingredients.Length; h++)
			{
				ret = ret + "\"" + ingredients[h].ID + "\"";

				if(h != ingredients.Length-1)
					ret = ret + ",";
			}

			ret = ret + "],\n";
			ret = ret + "\t\t\t\"product\" : \"" + combination.Item_Product.ID + "\"\n";

			ret = ret + "\t\t}";

			if(i != itemCombinations.Length-1)
				ret = ret + ",\n";
		}

		ret = ret + "\n\t]\n}";

		return ret;

	}

	public static string SanitizeString(string text)
	{
		text = text.Replace("&line", "\n");
		text = text.Replace("&quot", "\"");

		return text;
	}

}
